/**
 * ChatWindow UI 相关逻辑模块
 * 包含详情抽屉、对话框、UI 状态管理等功能
 */

import { ref, computed, type Ref, type ComputedRef } from 'vue'
import { useQuasar } from 'quasar'
import type { useChatStore } from '../stores/chat'

export interface UIModuleDeps {
  $q: ReturnType<typeof useQuasar>
  chatStore: ReturnType<typeof useChatStore>
  currentTargetId: ComputedRef<string | null>
  targetType: ComputedRef<'User' | 'Group'>
  targetName: ComputedRef<string>
  recentChatUsers: Ref<any[]>
  currentChatId: ComputedRef<string | null>
  groupMemberCountCache: Ref<Map<string, { count: number; timestamp: number }>>
  currentGroupMemberCount: Ref<number | undefined>
  groupMembersCache: Ref<Map<string, { alias?: string; displayName?: string; name?: string }>>
  updateRecentChatUsers: () => Promise<void>
  updateGroupMembersCache: (groupId: string, members: Array<{ member_id: string; alias?: string; displayName?: string; name?: string }>) => void
  // 群组模块的函数（需要调用）
  loadGroupDrawerDetails: (groupId: string, originalName?: string | null) => Promise<void>
  handleAddGroupMember: () => void
}

/**
 * 创建 UI 相关功能
 */
export function useChatWindowUI(deps: UIModuleDeps) {
  const {
    $q,
    chatStore,
    currentTargetId,
    targetName,
    recentChatUsers,
    currentChatId,
    groupMemberCountCache,
    currentGroupMemberCount,
    updateRecentChatUsers,
    loadGroupDrawerDetails: initialLoadGroupDrawerDetails,
    handleAddGroupMember: initialHandleAddGroupMember,
  } = deps

  // 将函数存储为 ref，以便在 groupModule 初始化后更新
  const loadGroupDrawerDetails = ref(initialLoadGroupDrawerDetails)
  const handleAddGroupMember = ref(initialHandleAddGroupMember)

  // 详情抽屉相关状态
  const showDetailsDrawer = ref(false)
  const detailsDrawerType = ref<'User' | 'Group' | null>(null)
  const detailsTargetId = ref<string | null>(null)
  const detailsTargetName = ref<string>('')
  const doNotDisturb = ref(false)
  const pinChat = ref(false)
  const groupMemberSearch = ref('')
  const groupDrawerMembers = ref<any[]>([])
  const currentGroupDrawerDetails = ref<any>(null)
  const showAllMembers = ref(false)
  const isGroupOwner = ref(false)
  const groupChatRemark = ref<string>('')

  // 对话框状态
  const showUserMenu = ref(false)
  const showHelp = ref(false)
  const showAddContactDialog = ref(false)
  const availableFriendsForAdd = ref<Array<{ id: string; name: string; remark?: string; avatar?: string; file_name?: string }>>([])

  // 处理显示详情面板（使用覆盖式抽屉，不挤压原窗口）
  const handleShowDetails = async (user: { id: string; name: string; chat_id?: string; chat_type?: number; member_count?: number }) => {
    detailsTargetId.value = user.id
    
    // 判断是否为群组：以 chat_type === 2 为主判断，人数只能作为辅助
    const isGroup = user.chat_type === 2 || 
                    (user.chat_type === undefined && user.id.startsWith('group_')) ||
                    (user.chat_type === undefined && !user.id.startsWith('group_') && 
                     user.member_count !== undefined && user.member_count !== null && user.member_count >= 3)
    
    // 直接从 recentChatUsers 中获取正确的名称（无论是好友还是群组）
    const chatInList = recentChatUsers.value.find(u => u.id === user.id)
    const displayName = chatInList?.name || user.name
    
    detailsTargetName.value = displayName
    detailsDrawerType.value = isGroup ? 'Group' : 'User'
    showDetailsDrawer.value = true
    
    console.log('handleShowDetails - 准备加载详情:', {
      userId: user.id,
      isGroup,
      detailsDrawerType: detailsDrawerType.value,
      chat_type: user.chat_type,
      member_count: user.member_count
    })
    
    if (detailsDrawerType.value === 'Group') {
      // 加载群组详情和成员（传递正确的名称）
      console.log('handleShowDetails - 开始加载群组详情:', user.id, 'loadGroupDrawerDetails:', loadGroupDrawerDetails.value)
      try {
        await loadGroupDrawerDetails.value(user.id, displayName)
        console.log('handleShowDetails - 群组详情加载完成')
      } catch (error) {
        console.error('handleShowDetails - 加载群组详情失败:', error)
      }
    } else {
      // 加载好友详情（如果需要）
      if (user.chat_id) {
        try {
          const { getUserChats } = await import('../services/im-chat')
          const chats = await getUserChats()
          const chat = chats.find(c => c.chat_id === user.chat_id)
          if (chat && (chat as any).remark) {
            groupChatRemark.value = (chat as any).remark
          } else {
            groupChatRemark.value = ''
          }
        } catch (error: any) {
          // 静默处理错误，不阻塞流程（可能是网络问题或服务器未启动）
          if (import.meta.env.DEV) {
            console.debug('获取聊天备注失败（静默处理）:', error.message || error)
          }
          groupChatRemark.value = ''
        }
      }
    }
  }

  // 处理显示详情（从聊天头部触发，点击3个横点切换抽屉）
  const handleShowDetailsFromHeader = () => {
    if (!currentTargetId.value) return
    
    if (showDetailsDrawer.value) {
      showDetailsDrawer.value = false
      return
    }
    
    const currentChat = recentChatUsers.value.find(u => u.id === currentTargetId.value)
    const chatName = (currentChat as any)?.name || targetName.value
    handleShowDetails({
      id: currentTargetId.value,
      name: chatName,
      chat_id: (currentChat as any)?.chat_id,
      chat_type: chatStore.targetType === 'Group' ? 2 : ((currentChat as any)?.chat_type || 1),
      member_count: (currentChat as any)?.member_count,
    })
  }

  // 处理查找聊天记录
  const handleSearchChatHistory = () => {
    $q.notify({
      type: 'info',
      message: '查找聊天记录功能待实现',
      position: 'top',
    })
  }

  // 处理清空聊天记录
  const handleClearChatHistory = () => {
    if (!detailsTargetId.value) return
    
    $q.dialog({
      title: '确认清空',
      message: `确定要清空与${detailsTargetName.value}的聊天记录吗？此操作只删除本地存储的消息，不会影响服务器上的消息。`,
      cancel: true,
      persistent: true,
    }).onOk(async () => {
      try {
        const { clearUserChatMessages, clearGroupChatMessages } = await import('../services/secure-storage')
        
        if (detailsDrawerType.value === 'Group') {
          const deletedCount = await clearGroupChatMessages(detailsTargetId.value!)
          await chatStore.clearUserMessages(detailsTargetId.value!, [])
          $q.notify({
            type: 'positive',
            message: `已清空群组聊天记录，共删除 ${deletedCount} 条消息`,
          })
        } else {
          await clearUserChatMessages(detailsTargetId.value!)
          await chatStore.clearUserMessages(detailsTargetId.value!, [])
          $q.notify({
            type: 'positive',
            message: '已清空聊天记录',
          })
        }
      } catch (error: any) {
        $q.notify({
          type: 'negative',
          message: error.message || '清空聊天记录失败',
        })
      }
    })
  }

  // 处理切换免打扰
  const handleToggleDoNotDisturb = (_value: boolean) => {
    // TODO: 实现免打扰设置
  }

  // 处理切换置顶
  const handleTogglePinChat = (_value: boolean) => {
    // TODO: 实现置顶设置
  }

  // 处理添加联系人（需要访问群组模块的函数）
  const handleAddContact = async () => {
    if (!detailsTargetId.value || !currentChatId.value) {
      $q.notify({
        type: 'warning',
        message: '请先选择一个聊天',
        position: 'top',
      })
      return
    }

    if (detailsDrawerType.value === 'Group') {
      handleAddGroupMember.value()
      return
    }

    try {
      const { getFriends } = await import('../services/im-friendship')
      const { getUserAsync } = await import('../services/auth')
      const { getGroupMembers } = await import('../services/im-group')
      
      const currentUser = await getUserAsync()
      if (!currentUser) {
        throw new Error('无法获取当前用户信息')
      }
      const currentUserId = currentUser.open_id || (currentUser.snowflake_id ? String(currentUser.snowflake_id) : undefined) || String(currentUser.id)
      
      let existingMemberIds: string[] = []
      try {
        const members = await getGroupMembers(detailsTargetId.value, false)
        existingMemberIds = members.map(m => m.member_id)
      } catch (e) {
        existingMemberIds = [currentUserId, detailsTargetId.value]
      }
      
      const friends = await getFriends()
      const { getUser } = await import('../services/message')
      
      const availableFriends = await Promise.all(
        friends
          .filter(f => {
            const friendId = f.user?.open_id || f.to_id
            return !existingMemberIds.includes(friendId) && friendId !== currentUserId
          })
          .map(async (f) => {
            const friendId = f.user?.open_id || f.to_id
            try {
              const userInfo = await getUser(friendId)
              return {
                id: friendId,
                name: f.remark || userInfo?.name || friendId,
                remark: f.remark,
              }
            } catch (e) {
              return {
                id: friendId,
                name: f.remark || friendId,
                remark: f.remark,
              }
            }
          })
      )
      
      // 即使没有可添加的好友，也显示对话框（显示空列表）
      const { getCachedImageUrl } = await import('../services/image-cache')
      const { API_BASE_URL } = await import('../config/env')
      const friendsWithAvatars = await Promise.all(
        availableFriends.map(async (f) => {
          try {
            const { getUser } = await import('../services/message')
            const userInfo = await getUser(f.id)
            let avatar: string | undefined = undefined
            if (userInfo?.file_name) {
              try {
                const url = `${API_BASE_URL}/api/upload/${userInfo.file_name}`
                avatar = await getCachedImageUrl(url)
              } catch (e) {
                console.error(`加载好友 ${f.id} 的头像失败:`, e)
              }
            }
            return {
              id: f.id,
              name: f.name,
              remark: f.remark,
              avatar,
              file_name: (userInfo as any)?.file_name,
            }
          } catch (e) {
            return {
              id: f.id,
              name: f.name,
              remark: f.remark,
            }
          }
        })
      )
      
      availableFriendsForAdd.value = friendsWithAvatars
      showAddContactDialog.value = true
    } catch (error: any) {
      console.error('获取好友列表失败:', error)
      $q.notify({
        type: 'negative',
        message: error.message || '获取好友列表失败',
        position: 'top',
      })
    }
  }

  // 处理添加联系人确认（需要访问群组模块的函数）
  const handleAddContactConfirm = async (
    selectedFriendId: string,
    loadGroupDrawerDetails: (groupId: string, originalName?: string | null) => Promise<void>
  ) => {
    try {
      const { addGroupMember } = await import('../services/im-group')
      
      const finalGroupId = await addGroupMember(currentChatId.value!, {
        member_id: selectedFriendId,
      })
      
      $q.notify({
        type: 'positive',
        message: '已添加联系人',
        position: 'top',
      })
      
      // 关闭添加对话框，但保持抽屉打开
      showAddContactDialog.value = false
      
      // 刷新最近聊天列表
      await updateRecentChatUsers()
      
      // 如果当前正在查看这个群组，刷新群成员列表和人数
      if (detailsTargetId.value && detailsDrawerType.value === 'Group') {
        // finalGroupId 已经通过 normalizeGroupId 标准化了（带 group_ 前缀），直接使用
        // 标准化群组ID用于比较（使用 finalGroupId，因为可能从2人升级到3人时ID会变化）
        const normalizedDetailsId = finalGroupId
        const normalizedCurrentId = currentTargetId.value 
          ? (currentTargetId.value.startsWith('group_') ? currentTargetId.value : `group_${currentTargetId.value}`)
          : null
        
        // 等待一小段时间，确保后端数据已更新
        await new Promise(resolve => setTimeout(resolve, 100))
        
        // 先更新群组信息（包括人数）
        try {
          const { getGroup } = await import('../services/im-group')
          const groupInfo = await getGroup(normalizedDetailsId)
          if (groupInfo && groupInfo.member_count !== undefined && groupInfo.member_count !== null) {
            // 更新人数缓存
            groupMemberCountCache.value.set(normalizedDetailsId, {
              count: groupInfo.member_count,
              timestamp: Date.now()
            })
            
            // 如果当前正在查看这个群组，更新显示的人数
            if (normalizedCurrentId === normalizedDetailsId && chatStore.targetType === 'Group') {
              currentGroupMemberCount.value = groupInfo.member_count
            }
          }
        } catch (e) {
          console.warn('更新群组人数失败:', e)
        }
        
        // 如果 detailsTargetId 和 finalGroupId 不同，更新 detailsTargetId
        if (detailsTargetId.value !== normalizedDetailsId) {
          detailsTargetId.value = normalizedDetailsId
        }
        
        // 重新加载群成员列表（强制刷新，不使用缓存）
        await loadGroupDrawerDetails(normalizedDetailsId)
      }
      
      // 如果添加成员后群组ID变化了（不太可能，但保留逻辑）
      if (finalGroupId !== currentChatId.value) {
        chatStore.currentTargetId = finalGroupId
        chatStore.targetType = 'Group'
        
        await loadGroupDrawerDetails(finalGroupId)
        detailsTargetId.value = finalGroupId
        try {
          const { getGroup } = await import('../services/im-group')
          const groupInfo = await getGroup(finalGroupId)
          detailsTargetName.value = groupInfo.group_name
        } catch (e) {
          console.warn('获取群组信息失败:', e)
        }
        detailsDrawerType.value = 'Group'
      }
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '添加联系人失败',
        position: 'top',
      })
    }
  }

  return {
    // 状态
    showDetailsDrawer,
    detailsDrawerType,
    detailsTargetId,
    detailsTargetName,
    doNotDisturb,
    pinChat,
    groupMemberSearch,
    groupDrawerMembers,
    currentGroupDrawerDetails,
    showAllMembers,
    isGroupOwner,
    groupChatRemark,
    showUserMenu,
    showHelp,
    showAddContactDialog,
    availableFriendsForAdd,
    // 函数
    handleShowDetails,
    handleShowDetailsFromHeader,
    handleSearchChatHistory,
    handleClearChatHistory,
    handleToggleDoNotDisturb,
    handleTogglePinChat,
    handleAddContact,
    handleAddContactConfirm,
    // 暴露 ref，以便在外部更新函数引用
    loadGroupDrawerDetails,
    handleAddGroupMember,
  }
}

